package org.sith.taskrunner.gwt.client.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;

import java.util.List;


public abstract class TableWidget<T> extends Composite implements ITableView<T> {


    private static final int PAGE_SIZE = 20;
    private ListDataProvider<T> userEntityProxyListDataProvider;
    private SingleSelectionModel<T> selectionModel;

    interface TableWidgetUiBinder extends UiBinder<HTMLPanel, TableWidget> {
    }

    private static TableWidgetUiBinder ourUiBinder = GWT.create(TableWidgetUiBinder.class);


    CellTable<T> cellTable;
    @UiField
    VerticalPanel tablePanel;
    @UiField
    HorizontalPanel contolPanel;


    public TableWidget() {
        initWidget(ourUiBinder.createAndBindUi(this));
        cellTable = new CellTable<T>();
        selectionModel = new SingleSelectionModel<T>();

        cellTable.setSelectionModel(selectionModel);
        SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
        SimplePager pager = new SimplePager(SimplePager.TextLocation.CENTER, pagerResources, false, 0, true);
        pager.setDisplay(cellTable);
        pager.setPageSize(PAGE_SIZE);
        pager.setPageStart(0);

        configureColumns(cellTable);

        cellTable.setPageSize(PAGE_SIZE);
        userEntityProxyListDataProvider = new ListDataProvider<T>();
        userEntityProxyListDataProvider.addDataDisplay(cellTable);

        contolPanel.add(pager);
        addControlsToTable(contolPanel);
        tablePanel.add(cellTable);

    }

    protected abstract void configureColumns(CellTable<T> cellTable);


    public void setTableData(List<T> users) {
        cellTable.setRowData(0, users);
        userEntityProxyListDataProvider.setList(users);

    }


    protected abstract void addControlsToTable(HasWidgets widget);

    protected T getSelectedObject(){
        return  selectionModel.getSelectedObject();
    }

}